/**  
 * @Title:  WeChartMinAppController.java   
 * @Package com.platform.controller   
 * @Description: (用一句话描述该文件做什么)   
 * @author: <a href="mailto:15909910367@163.com">吴先生</a> 
 * @date:   2021年2月3日 下午12:27:18   
 * @version V1.0 
 * @Copyright: 2021 吴先生.
 */
package com.platform.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSONObject;
import com.platform.base.Constants;
import com.platform.base.R;
import com.platform.config.WechatConfig;
import com.platform.dto.Right;
import com.platform.dto.User;
import com.platform.security.CipherUtil;
import com.platform.service.IRight;
import com.platform.service.IUser;
import com.platform.utils.ArrayUtils;
import com.platform.utils.TokenManager;

import cn.hutool.core.map.MapUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**   
 * @ClassName:  WeChartMinAppController   
 * @Description:微信小程序相关接口
 * @author: <a href="mailto:15909910367@163.com">吴先生</a>  
 * @date:   2021年2月3日 下午12:27:18   
 *     
 * @Copyright: 2021 吴元森.  
 */
@Api(tags="COMMON-微信相关接口")
@Controller
@RequestMapping("wechatMinApp")
public class WeChatMinAppController {

	@Autowired
	private IUser userService;
	@Autowired
	private IRight rightService;
	
	/**
	 * @Title: login   
	 * @Description: 获取凭证校检接口 微信小程序登录接口   
	 * @author: <a href="mailto:15909910367@163.com">吴先生</a>
	 * @param code	登录凭证（code）。通过凭证进而换取用户登录态信息，包括用户的唯一标识（openid）及本次登录的会话密钥（session_key）等。
	 * 用户数据的加解密通讯需要依赖会话密钥完成
	 * @return      
	 * R<?>
	 */
	@PostMapping(value = "login")
	@ApiOperation(value="登录")
	@ApiImplicitParams({
        @ApiImplicitParam(name = "code", value = "登录凭证", required = true, dataType = "String")
	})
	@ResponseBody
	public R<?> login(String code){
		//调用微信接口获取openid
		String url = WechatConfig.get("weixin_login_url")+"appid="+WechatConfig.get("weixin_samll_program_appid")+
				"&secret="+WechatConfig.get("weixin_samll_program_secret")+"&js_code=" + code + 
				"&grant_type="+WechatConfig.get("weixin_samll_program_granttype");
		RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问url接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        //根据返回值进行后续操作
        if (responseEntity != null && responseEntity.getStatusCode() == HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            JSONObject jsonObject = JSONObject.parseObject(sessionData);
            System.out.println(jsonObject.toJSONString());
            return R.success(jsonObject.getString("openid"));
        }else {
        	return R.fail("unkonw openid");
        }
	}
	
	@GetMapping("loadUserInfo")
	@ApiOperation("加载用户信息")
	@ApiImplicitParams({
		@ApiImplicitParam(name="openid",value="用户凭证",required=true,dataType="String")
	})
	@ResponseBody
	public R<?> loadUserInfo(String openid){
		User user = userService.selectUserByOpenId(openid);
		if(user != null) {
			List<Right> rightList = rightService.findRightByUserCode(user.getId()+"");
			List<String> sourcesSb = new ArrayList<String>();
			for(Right ri : rightList){
				sourcesSb.add(ri.getSourcescode());
			}
			ArrayUtils.removeDuplicate(sourcesSb);
			Map<String,Object> claims = MapUtil.newHashMap();
			claims.put(Constants.JWT_USER_NAME, user.getRealname());
			claims.put(Constants.JWT_USER_KEY, user);//这里存放的是权限字信息
			claims.put(Constants.JWT_PERMISSIONS_KEY, sourcesSb);
	        String token = TokenManager.getAccessToken(user.getId()+"", claims);
			return R.success(user).setExtra(token);
		}else {
			return R.fail("未能找到对应用户");
		}
	}
	
	@GetMapping("authorizedRegister")
	@ApiOperation("绑定系统用户")
	@ApiImplicitParams({
		@ApiImplicitParam(name="openid",value="用户凭证",required=true,dataType="String"),
		@ApiImplicitParam(name="userName",value="用户名",required=true,dataType="String"),
		@ApiImplicitParam(name="password",value="密码",required=true,dataType="String")
	})
	@ResponseBody
	public R<?> authorizedRegister(String openid,String userName,String password){
		User user = userService.selectUserByOpenId(openid);
		if(user == null) {
			User validataUserName = userService.validateUserName(userName);
			if(validataUserName != null) {
				User validedUser = userService.validateUserNameAndPwd(userName, CipherUtil.generatePassword(password));
				if(validedUser != null) {
					if(validedUser.getJobstate().equals(3L)){
						return R.fail("用户["+validedUser.getLoginname()+"]已锁定，不能登录到系统中");
					}else if(validedUser.getJobstate().equals(2L)){
						return R.fail("用户["+validedUser.getLoginname()+"]已离职，不能登录到系统中");
					}else{
						User updateOpenIdUser = new User();
						updateOpenIdUser.setId(validedUser.getId());
						updateOpenIdUser.setOpenId(openid);
						if(userService.update(updateOpenIdUser)) {
							return R.success("授权注册成功");
						}else {
							return R.fail("授权注册失败/服务器异常");
						}
					}
				}else {
					return R.fail("密码错误");
				}
			}else {
				return R.fail("用户不存在");
			}
		}else {
			return R.fail("已经注册不在进行注册");
		}
	}
}
